# Specify the process names, output file, and retry settings
$processNames = @("chromedriver", "chrome", "java")     # Add all the process names to monitor
$outputFile = "C:\Users\GY\Desktop\test_result\Selenium\testcase_three3.csv"
$timeoutSeconds = 60  # Maximum time to wait for any process (in seconds)
$retryInterval = 1    # Time between retries (in seconds)

# Write the header to the CSV
"Elapsed Time (s)`tTotal CPU Usage (%)`tTotal Memory Usage (MB)`tTotal Thread Count" | Out-File $outputFile

# Initialize retry timer
$startTime = Get-Date
$processFound = $false

# Wait and retry to find any of the processes
while (((Get-Date) - $startTime).TotalSeconds -lt $timeoutSeconds) {
    # Check if any of the processes are running
    $processes = Get-Process -Name $processNames -ErrorAction SilentlyContinue

    if ($processes) {
        Write-Host "One or more processes found. Starting monitoring..."
        $processFound = $true
        break
    } else {
        Write-Host "No specified processes found. Retrying in $retryInterval seconds..."
        Start-Sleep -Seconds $retryInterval
    }
}

# Exit if no processes are found within the timeout
if (-not $processFound) {
    Write-Host "No specified processes found after $timeoutSeconds seconds. Exiting."
    exit
}

# Monitor the processes
$monitorStartTime = Get-Date

while ($true) {
    # Get all matching processes
    $processes = Get-Process -Name $processNames -ErrorAction SilentlyContinue

    if ($processes) {
        # Initialize cumulative metrics
        $totalCPU = 0
        $totalMemory = 0
        $totalThreads = 0

        foreach ($process in $processes) {
            # Accumulate metrics
            $totalCPU += $process.CPU
            $totalMemory += $process.WorkingSet / 1MB  # Convert to MB
            $totalThreads += $process.Threads.Count
        }

        # Calculate elapsed time in seconds
        $elapsedTime = [math]::Round(((Get-Date) - $monitorStartTime).TotalSeconds, 2)

        # Log cumulative data to CSV
        "$elapsedTime`t$totalCPU`t$totalMemory`t$totalThreads" | Out-File $outputFile -Append
    } else {
        Write-Host "No specified processes found. Exiting monitoring loop."
        break
    }

    Start-Sleep -Seconds 1
}
